import { 
    StatusBar,
    StyleSheet, 
    Text, 
    View ,
    Image,
    TextInput,
    TouchableHighlight,
    FlatList,
    Modal,
    Alert
  } from 'react-native';
  import {useState,useEffect} from 'react';
  import axios from 'axios';
  import '../../global';
  import ModalDropdown from 'react-native-modal-dropdown';

  export default function Cnode() {
    const [isPress,setPress] = useState(0)
    const [tab,setTab] = useState('')
    const [getData,setGetData] = useState('')
    const [modalVisible,setModalVisible] = useState(false)
    const [title,setTitle] = useState('')
    const [text,setText] = useState('')
    const [postTab,setPostTab] = useState('')

    const handlePress=async(id)=>{
      setPress(id)
      if(id!==0){
        switch(id){
          case 1:
            setTab('good')
            break;
          case 2:
            setTab('share')
            break;
          case 3:
            setTab('ask')
            break;
          case 4:
            setTab('job')
            break;
        }
        try{
          const response = await axios.get(`https://cnodejs.org/api/v1/topics?tab=${tab}`)
          setGetData(response.data.data)
   
        }catch(error){
          console.error('error',error)
        }
      }else{
        try{
          const response = await axios.get(`https://cnodejs.org/api/v1/topics`)
          setGetData(response.data.data)
        }catch(error){
          console.error('error',error)
        }
      }
    }
  
    const axiosAllBtn=async()=>{
      try{
        const response = await axios.get(`https://cnodejs.org/api/v1/topics`)
        setGetData(response.data.data)
      }catch(error){
        console.error('error',error)
      }
    }
    const renderList = ({item})=>{
      let timeAgo = ''
      const lastReplyTime = new Date(item.last_reply_at)
      const currentTime = new Date()
      const timeDiff = currentTime.getTime()-lastReplyTime.getTime()
      const secondDiff = Math.floor(timeDiff/1000)
      const minuteDiff = Math.floor(secondDiff/60)
      const hourDiff = Math.floor(minuteDiff / 60);
      const dayDiff = Math.floor(hourDiff / 24);
      const monthDiff = Math.floor(dayDiff/30);
      const yearDiff = Math.floor(monthDiff/12)
      if(yearDiff>0){
        timeAgo = yearDiff+'年前'
      }else if(monthDiff>0){
        timeAgo = monthDiff+'月前'
      }else if(dayDiff>0){
        timeAgo = dayDiff+'天前'
      }
      else if(hourDiff>0){
        timeAgo = hourDiff+'小时前'
      }
      else if(secondDiff>0){
        timeAgo = secondDiff+'秒前'
      }
      return (
        <View
          style={{
            margin:16,
          }}
        >
          <View
          style={{
            flexDirection:'row',
            alignItems:'center',
            
          }}
        >
          <Image 
            source={{uri:item.author.avatar_url.toString()}}
            defaultSource={require('../../assets/icon.png')}
            style={{borderColor:'black',borderEndWidth:2,width:45,height:45,borderRadius:4,marginRight:18}}
          />
          
          <Text 
            style={{
              backgroundColor:'#E5E5E5',
              color:'#999999',
              width:35,
              height:22,
              textAlign:'center',
              lineHeight:22,
              borderRadius:4,
              marginRight:18
            }}
          >
            {item.tab === 'share'?'分享':item.tab==='ask'?'问答':item.tab==='good'?'精华':item.tab==='job'?'招聘':''}
          </Text>
          <Text>
            {item.title.length>23?item.title.slice(0,23)+'...':item.title}
          </Text>
          <Text 
            style={{
              position:'absolute',
              left:450,
              top:30,
              color:'#828282'
            }}
          >
            {timeAgo}
          </Text>
          </View>
          <View style={{flexDirection:'row',position:'relative',left:116,top:-10}}>
            <Text style={{color:'#9E78C0'}}>
              {item.reply_count}
            </Text>
            <Text style={{color:'#333333'}}>/</Text>
            <Text style={{color:'#B4B4B4'}}>
              {item.visit_count}
            </Text>
          </View>
          <View style={{ borderBottomWidth: 1, borderBottomColor: '#E5E5E5',width:800,position:'relative',top:-5 }} />
        </View>
      )
    }

    const publishOne=()=>{
        console.log('去发布')
        setModalVisible(true)
    }

    const goBack=()=>{
      setModalVisible(false)
      setTitle('')
      setText('')
      setPostTab('')
      console.log('退出',title,postTab,text)
    }

    const onChangeTitle = (title)=>{
      setTitle(title)
    }

    const onChangeText=(text)=>{
      setText(text)
    }
    const selectOption=(index,value)=>{
      switch(index){
        case 1:
          setPostTab('share')
          break;
        case 2:
          setPostTab('ask')
          break;
        case 3:
          setPostTab('job')
          break;
        case 4:
          setPostTab('dev')
          break;
        default:
          setPostTab('')
      }
      console.log('posttab',postTab)
    }

    const postForm=()=>{
      if(title.length<10){
        Alert.alert('标题字数10字以上！')
      }else if(text.length<1){
        Alert.alert('话题内容不能为空！')
      }else if(!postTab){
        Alert.alert('请选择一个版块！')
      }else{
        let form = {
          accesstoken:'3bc1ce9b-40f1-422c-9f7d-57e1d6798cef',
          title:title,
          tab:postTab,
          content:text
        }
        console.log('form',form)
        axios.post('https://cnodejs.org/api/v1/topics',form)
        .then(function (response) {
          console.log('response',response);
          if(response.status==200){
            Alert.alert('发布成功！')
            goBack()
          }
        })
        .catch(function (error) {
          console.log(error);
        });
      }
      

    }
    useEffect(()=>{
      axiosAllBtn()
    },[])
    return (
      <View style={styles.container}>
        <View style={styles.hearder}>
          <Image
            source={require('../../assets/cnodeLogo.png')}
            style={{
              alignSelf:'center',
              marginTop:20,
              width:180,
              height:50
            }}
            />
          <TextInput
            style={{
              width:320,
            //   width:px2dp(500),
              height:35,
              borderRadius:25,
              backgroundColor:'#888888',
              alignSelf:'center',
              paddingHorizontal:30,
              marginTop:10
            }}
          />
          <View style={styles.headBody}>
            <Text style={styles.headBodyItem}>首页</Text>
            <Text style={styles.headBodyItem}>未读消息</Text>
            <Text style={styles.headBodyItem}>新手入门</Text>
            <Text style={styles.headBodyItem}>API</Text>
            <Text style={styles.headBodyItem}>关于</Text>
            <Text style={styles.headBodyItem}>设置</Text>
            <Text style={styles.headBodyItem}>退出</Text>
          </View>
          <StatusBar/>
        </View>
        <TouchableHighlight
            underlayColor='#A1A1A1'
            backgroundColor='#DDDDDD'
            style={{
              position:'absolute',
              backgroundColor:'#D3D3D3',
              width:60,
              height:60,
              top:600,
              borderRadius:5,
              left:370,
              zIndex:999,
              opacity:0.9
            }}
            onPress={publishOne}
        >
          <Text style={{alignSelf:'center',lineHeight:60,color:'#8E8E8E'}}>发布</Text>
        </TouchableHighlight>
        <Modal
          animationType='none'
          transparent={true}
          visible={modalVisible}
          onRequestClose={()=>{
            setModalVisible(!modalVisible)
          }}
        >
          <View
            style={{
              backgroundColor:'#FFFFFF',
              width:434,
              height:550,
              marginTop:250,
              marginLeft:8,
              marginRight:8,
              
              
            }}
          >
            <View style={{
              flexDirection:'row',
              backgroundColor:"#F6F6F6",
              borderBottomWidth:1,
              borderBottomColor:'#E5E5E5'
            }}>
              <Text style={{color:'#9DC95D',margin:6,marginLeft:14,fontSize:17}}>主页</Text>
              <Text style={{color:'#999999',margin:6,fontSize:17}}>/</Text>
              <Text style={{color:'#999999',margin:6,fontSize:17}}>发布话题</Text>
            </View>
            <View 
            style={{
              height:50
            }}>
              <Text style={{
                lineHeight:40,
                marginLeft:18,
                marginTop:5
              }}>选择版块:</Text>
              <ModalDropdown 
                options={['请选择','分享','问答','招聘','客户端测试']}
                defaultIndex={0}
                defaultValue='请选择'
                style={{
                  borderColor:'#DADADA',
                  borderRadius:4,
                  borderWidth:1,
                  width:160,
                  height:30,
                  position:'relative',
                  left:88,
                  top:-35,
                  borderRadius:3
                }}
                textStyle={{
                  fontSize:15,
                  lineHeight:26,
                  marginLeft:4,
                  color:'#6C6C6C'
                }}
                dropdownStyle={{
                  width:100,
                  fontSize:20,
                  lineHeight:26,
                  marginLeft:4,
                  color:'#6C6C6C'
                }}
                onSelect={selectOption}
              />
            </View>
            <TextInput
              minLength={10}
              placeholder='标题字数10字以上'
              onChangeText={title=>onChangeTitle(title)}
              textAlignVertical='top'
              style={{
                // backgroundColor:'yellow'
                width:400,
                height:25,
                lineHeight:25,
                borderColor:'#DADADA',
                borderWidth:1,
                marginLeft:20,
                padding:2,
                borderRadius:3
              }}
            />
            <TextInput
              placeholder='输入话题内容'
              onChangeText={text=>onChangeText(text)}
              multiline={true}
              textAlignVertical='top'
              style={{
                width:400,
                height:340,
                lineHeight:25,
                borderColor:'#DADADA',
                borderWidth:1,
                marginLeft:20,
                marginTop:10,
                padding:10,
                borderRadius:4
              }}
            />
            <TouchableHighlight
              underlayColor='#ACACAC'
              backgroundColor='#888888'
              style={{
                position:'relative',
                backgroundColor:'#D3D3D3',
                width:150,
                height:40,
                marginTop:20,
                marginLeft:20
              }}
              onPress={goBack}
            >
              <Text style={{alignSelf:'center',lineHeight:40,color:'#7B7B7B'}}>退出</Text>
            </TouchableHighlight>
            <TouchableHighlight
              underlayColor='#ACACAC'
              backgroundColor='#888888'
              style={{
                position:'relative',
                backgroundColor:'#D3D3D3',
                width:150,
                height:40,
                marginTop:-40,
                marginLeft:270

              }}
              onPress={postForm}
            >
              <Text style={{alignSelf:'center',lineHeight:40,color:'#7B7B7B'}}>发布</Text>
            </TouchableHighlight>
          </View>
        </Modal>
        <View style={styles.body}>
          <View style={styles.bodyTitle}>
            <TouchableHighlight
              style={isPress==0 ? styles.buttonPressed : styles.button}
              onPress={()=>handlePress(0)}
            >
              <Text style={isPress==0 ? styles.buttonTextPressed : styles.buttonText}>全部</Text>
            </TouchableHighlight>
            <TouchableHighlight
              style={isPress==1 ? styles.buttonPressed : styles.button}
              onPress={()=>handlePress(1)}
            >
              <Text style={isPress==1 ? styles.buttonTextPressed : styles.buttonText}>精华</Text>
            </TouchableHighlight>
            <TouchableHighlight
              style={isPress==2 ? styles.buttonPressed : styles.button}
              onPress={()=>handlePress(2)}
            >
              <Text style={isPress==2 ? styles.buttonTextPressed : styles.buttonText}>分享</Text>
            </TouchableHighlight>
            <TouchableHighlight
              style={isPress==3 ? styles.buttonPressed : styles.button}
              onPress={()=>handlePress(3)}
            >
              <Text style={isPress==3 ? styles.buttonTextPressed : styles.buttonText}>问答</Text>
            </TouchableHighlight>
            <TouchableHighlight
              style={isPress==4 ? styles.buttonPressed : styles.button}
              onPress={()=>handlePress(4)}
            >
              <Text style={isPress==4 ? styles.buttonTextPressed : styles.buttonText}>招聘</Text>
            </TouchableHighlight>
            
          </View>
          <View style={styles.bodyText}>
            <FlatList
              data={getData}
              renderItem={renderList}
              keyExtractor={(item)=>item.id}
            />
          </View>
        </View>
      </View>
    );
  }
  
  // native中布局元素默认就是弹性盒
  
  const styles = StyleSheet.create({
    container:{
      backgroundColor:'#E1E1E1'
    },
    hearder:{
      backgroundColor:'#444444',
      height:230,
      marginLeft:8,
      marginRight:8,
    },
    headBody:{
      flexDirection:'row',
      width:450,
      height:200,
      flexWrap:'wrap',
      marginLeft:48,
      marginTop:16
  
    },
    headBodyItem:{
      color:'#CCCCCC',
      height:50,
      fontSize:18,
      marginLeft:20,
      marginRight:20
    },
    body:{
      marginTop:26,
      backgroundColor:'#F6F6F6',
      minHeight:600,
      marginLeft:8,
      marginRight:8,
      // height:50,
      borderRadius:3
    },
    bodyTitle:{
      flexDirection:'row',
      flexWrap:'wrap',
      alignSelf:'center',
      height:50
    },
    button:{
      backgroundColor:'#F6F6F6',
      width:40,
      height:22,
      borderRadius:3,
      alignItems:'center',
      marginLeft:20,
      marginRight:20,
      marginTop:15
    },
    buttonPressed:{
      backgroundColor:"#80BD01",
      width:40,
      height:22,
      borderRadius:3,
      alignItems:'center',
      marginLeft:20,
      marginRight:20,
      marginTop:15
    },
    buttonText:{
      color:'#80BD01',
      fontSize:15
    },
    buttonTextPressed:{
      color:'#F6F6F6',
      fontSize:16
    },
    bodyText:{
      backgroundColor:'#FFFFFF'
    }
  });